package org.zjx.action.game.gather;

import org.zjx.analysis.window.PetAnalysis;
import org.zjx.action.game.AbstractWindowAction;
import org.zjx.core.IWindow;
import org.zjx.model.game.Pet;
import org.zjx.state.PetState;

import java.awt.*;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;

public class GatherPetAction extends AbstractWindowAction {
    private PetAnalysis petAnalysis;
    
    public GatherPetAction(IWindow targetWindow) {
        super(targetWindow);
    }

    private void analysis() {
        petAnalysis = new PetAnalysis(targetWindow, stateManager.getGameState().getScreenshot());
    }

    @Override
    public void open() {
        analysis();
        mouseAloofWindow(petAnalysis.windowArea == null? petAnalysis.getOriginBounds(): petAnalysis.windowArea);
        if (petAnalysis.isOpened()) return;
        hotkey(KeyEvent.VK_ALT, KeyEvent.VK_O);
        flush();
        open();
    }

    @Override
    public void close() {
        analysis();
        if (!petAnalysis.isOpened()) return;
        hotkey(KeyEvent.VK_ALT, KeyEvent.VK_O);
        flush();
        close();
    }

    @Override
    public void reSetWindow() {
        if (petAnalysis.isTransborder()) {
            drag(petAnalysis.conversion(petAnalysis.windowArea,petAnalysis.getRefImageArea()), petAnalysis.conversion(petAnalysis.getOriginBounds(),petAnalysis.getRefImageArea()));
            analysis();
        }
    }

    public void mouseAloofWindow(Rectangle rect) {
        if (petAnalysis.mouseInRect(rect)) {
            Point safePoint = petAnalysis.findLargestRemainingAreaCenter(rect);
            move(safePoint);
        }
    }

    @Override
    protected void doExecute() throws Exception {
        if (stateManager.getGameState().isGatherPet()) return;
        open();
        reSetWindow();
        PetState petState = new PetState();
        stateManager.registerState(petState);
        
        List<Pet> pets = new ArrayList<>();
        for (int i = 0; i < Math.min(petAnalysis.getPetCount(),4);i++){
            while (petAnalysis.getChoosePetIndex() != i){
                click(petAnalysis.petIndex(i));
                flush();
                analysis();
            }
            pets.add(petAnalysis.getPet());
        }
        petState.setPets(pets);
        close();
        stateManager.getGameState().setGatherPet(true);
    }
}
